<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import { debounce } from '@/utils'
import echarts from 'echarts'

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    chartData:{
      type: Array,
      default: function () { return [] }
    }
  },
  data() {
    return {
      chart: null,
      seriesData: [],
      xAxisData: [],
    }
  },
  watch: {
    "chartData": {
      handler(newVal, oldVal) {
        console.log('newVal',newVal)
        if(newVal.length > 0){
          this.seriesData= []
          this.xAxisData = []
          const _this = this

          newVal.forEach((item) => {
            _this.seriesData.push(item.qty)
            _this.xAxisData.push(item.ts_week)
            // console.log(item)
          })
          // console.log(this.chartOption)
          this.initChart()
        }
      }
    }
  },
  mounted() {

    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {

    initChart() {
      this.chart = echarts.init(this.$el, 'dark')
      this.chart.setOption({
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'axis',
          formatter: params => `
            ${params[0].axisValue}
            <br />
            ${params[0].marker} 农机上线数: ${params[0].data} 台
          `
        },
        xAxis: {
          type: 'category',
          data: this.xAxisData
        },
        yAxis: {
          type: 'value',
          name: '台'
        },
        series: [
          {
            data: this.seriesData,
            type: 'line'
          }
        ]
      })
    }
  }
}
</script>
